package model

import (
	"database/sql/driver"
	"fmt"
	"gin-vue-admin/global"
	"time"
)

const TimeFormat = "2006-01-02 15:04:05"
const DateFormat = "2006-01-02"

type LocalTime time.Time

func (t *LocalTime) UnmarshalJSON(data []byte) (err error) {
	var now time.Time

	sdata := string(data)
	global.GVA_LOG.Info(sdata)
	// global.GVA_LOG.Info("----------- 解析json, %v", string(data))
	if len(data) == 2 {
		*t = LocalTime(time.Time{})
		return
	}

	slen := len(sdata)
	fmt.Printf("  |--> len: %v, data=\n", slen, sdata)
	if slen == 12 {
		now, err = time.Parse(`"`+DateFormat+`"`, sdata)
	} else {
		now, err = time.Parse(`"`+TimeFormat+`"`, sdata)
	}
	*t = LocalTime(now)
	fmt.Printf("  |--> time: %v\n", t.String())
	// global.GVA_LOG.Info("----------- t, %v", t)
	// global.GVA_LOG.Info("----------- t, %v", t)
	return
}

func (t LocalTime) MarshalJSON() ([]byte, error) {
	//	sdata := string(b)
	//	fmt.Printf("  |--> time: %v\n", t.String())
	fmt.Printf("  |--> t= %v\n", t)
	b := make([]byte, 0, len(TimeFormat)+2)
	b = append(b, '"')
	b = time.Time(t).AppendFormat(b, TimeFormat)
	b = append(b, '"')
	return b, nil
}

func (t LocalTime) Value() (driver.Value, error) {
	if t.String() == "0001-01-01 00:00:00" {
		return nil, nil
	}
	return []byte(time.Time(t).Format(TimeFormat)), nil
}

func (t *LocalTime) Scan(v interface{}) error {
	tTime, _ := time.Parse("2006-01-02 15:04:05 +0800 CST", v.(time.Time).String())
	*t = LocalTime(tTime)
	return nil
}

func (t LocalTime) String() string {
	return time.Time(t).Format(TimeFormat)
}
